package cn.lsj.readwriteseparation.controller;

import cn.lsj.readwriteseparation.entity.Dict;
import cn.lsj.readwriteseparation.entity.User;
import cn.lsj.readwriteseparation.model.bo.UserAddressBO;
import cn.lsj.readwriteseparation.service.AddressService;
import cn.lsj.readwriteseparation.service.DictService;
import cn.lsj.readwriteseparation.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.AllArgsConstructor;
import org.apache.shardingsphere.api.sharding.ShardingAlgorithm;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.List;

/**
 * @className: TestController
 * @description: 验证
 * @author: liangshijie
 * @date: 2022/12/5
 **/
@RequestMapping("test")
@AllArgsConstructor
@RestController
public class TestController {

    private final UserService userService;
    private final AddressService addressService;
    private final DictService dictService;

    /**
     * 广播表
     */
    @PostMapping("broadcast")
    public Boolean broadcast(@RequestBody Dict dict) {
        return dictService.saveOrUpdate(dict);
    }

    /**
     * join查询
     */
    @GetMapping("join")
    public List<UserAddressBO> page(@Valid @NotNull @RequestParam("userId") Long userId) {
        return addressService.getUserAddress(userId);
    }

    /**
     * 根据上一个id进行分页查询
     */
    @GetMapping("page")
    public List<User> page(@RequestParam("size") Integer size,
                     @Valid @NotNull @RequestParam("id") Long id) {
        LambdaQueryWrapper<User> last = Wrappers.<User>lambdaQuery().gt(User::getId, id).last(" limit " + size);
        return userService.list(last);
    }


    /**
     * limit分页查询
     */
    @GetMapping("page2")
    public IPage<User> page(
                        @RequestParam("current") Integer current,
                        @RequestParam("size") Integer size) {

        Page page = new Page<>();
        page.setSize(size);
        page.setCurrent(current);
        return userService.page(page);
    }

    @GetMapping("read/{id}")
    public User read(@PathVariable("id") Long id) {
        return userService.getById(id);
    }

    /**
     * 插入一条数据
     */
    @PostMapping("write")
    public String write(@RequestBody User user) {
        userService.saveOrUpdate(user);
        ShardingAlgorithm a;
        return "成功";
    }

    /**
     * 插入一批数据
     */
    @PostMapping("writeBatch/{index}")
    public String writeBatch(@PathVariable("index") Integer index) {
        User user;
        for(int i = index; i < index + 1000; i++) {
            user = new User();
            user.setUsername(i + "");
            userService.save(user);
        }
        return "成功";
    }
}
